// pages/detail/detail.js
// pages/about/about.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    firstTurnOffTime:'',
    secondTurnOffTime:'',
    firstTurnOnTime:'',
    secondTurnOnTime:'',
    devNo:'',
    latitude:'',
    longitude:'',
    type:'',
    devCurrentTime:'',
    firstOrSumElec:'',
    auto:'',
    onLine:'',
    firstSwitch:'',
    secondSwitch:'',
    description:'',
    address:'',
    secondElec:'',
    cur_mode_array: ['手动', '自动'],
    /**模式默认的值 默认是手动 */
    cur_mode_index:0,
    cur_mode_item:'手动',  
    cur_operator:['合上','断开'],
    /**状态默认值  默认是合上*/
    cur_operator_index:0,
    cur_operator_item:'合上',

    index: 0,
    date: '2016-09-01',
    time: '12:01',
    interval:30,
    mode_disabled:false,
    switch_disabled:false,
    turnon_disabled:false,
    turnoff_disabled:false,

    before_firstTurnOnTime:'',
    before_firstTurnOffTime:'',
    before_longitude:'',
    before_latitude:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

  /**这个是从详细设置点进来的情况*/    
    let current_info = options.current_info;
    let address = options.address;
    let parse_current_info = JSON.parse(current_info);     
    
    that.setData({
      firstTurnOffTime: parse_current_info.firstTurnOffTime,
      secondTurnOffTime: parse_current_info.secondTurnOffTime,
      firstTurnOnTime: parse_current_info.firstTurnOnTime,
      secondTurnOnTime: parse_current_info.secondTurnOnTime,
      before_firstTurnOffTime: parse_current_info.firstTurnOffTime, 
      before_firstTurnOnTime: parse_current_info.firstTurnOnTime,
      devNo: parse_current_info.devNo,
      latitude: parse_current_info.latitude,
      longitude: parse_current_info.longitude,
      before_latitude: parse_current_info.latitude,
      before_longitude: parse_current_info.longitude,
      type: parse_current_info.type,
      devCurrentTime: parse_current_info.devCurrentTime,
      firstOrSumElec: parse_current_info.firstOrSumElec,
      auto: parse_current_info.auto,
      onLine: parse_current_info.onLine,
      firstSwitch: parse_current_info.firstSwitch,
      secondSwitch: parse_current_info.secondSwitch,
      description: parse_current_info.description,
      address: parse_current_info.address,
      secondElec: parse_current_info.secondElec
    });

    if(that.data.onLine == false){
      wx.showModal({
        title: '提示',
        content: '设备不在线，无法设置开关时间及定位！',
      });
      return;
    }

    /**['手动', '自动']*/
    if (that.data.auto == true){
      that.setData({
        cur_mode_index: 1,
        cur_mode_item:"自动"       
        //cur_operator_index: 0,        
      });
    }

    /**['合上','断开'], */
    if(that.data.onLine == false){
      that.setData({
        cur_operator_index:1,
        cur_operator_item:"断开"
      });     
    }

    if(that.data.onLine == false){
      that.setData({
        mode_disabled:true,
        switch_disabled: true,
        turnon_disabled: true,
        turnoff_disabled: true
      });
    }

    // if(that.data.onLine == false){
    //  wx.showModal({
    //    title: '提示',
    //    content: '离线设备只能设置经纬度',
    //  })
    // }
  },

  //打开新一页 页面是地图获取经纬度
  set_Longitude_getLatitude:function(){    
    wx.navigateTo({
      url:"../get_longi_lati/get_longi_lati"
    });
  },

  bindPickerChange(e) {    
    this.setData({
      index: e.detail.value
    })
  },

  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },

  bindTimeChange(e) {
    this.setData({
      time: e.detail.value
    })
  },

  show_map:function(){
    let that = this;
    if(that.data.onLine == false){
      return;
    }
    wx.navigateTo({
      url: '../get_longi_lati/get_longi_lati',
    });
  },

  apply_config:function(){
    let that = this;   
    if(that.data.onLine == false){
      wx.showModal({
        title: '提示',
        content: '设备不在线，无法应用配置，请返回上一页',
      });
      return;
    } 

    wx.showToast({
      title: '请稍等...',
      mask: true,
      icon: 'loading',
      duration: 5000
    });
    
    //m_set_dev_on 打开设备开关
    //m_set_dev_off 关闭设备开关
    //m_set_dev_auto  设备开关改为自动
    //m_set_dev_manual 设备开关改为手动
    //m_set_dev_timer 设置设备开关时间
    //m_set_dev_location  设置设备的经纬度    
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };    

    let m_set_dev_on_off_url = '';

    /**cur_operator [合上，断开] */
    // if(that.data.cur_operator_index == 0){
    //   m_set_dev_on_off_url = "https://119.3.46.145/server/m_set_dev_on?devId=" + that.data.devNo;
    // }
    // if (that.data.cur_operator_index == 1){
    //   m_set_dev_on_off_url = "https://119.3.46.145/server/m_set_dev_off?devId=" + that.data.devNo;
    // }

    // if (onlineDevice.indexOf(devNo) === -1) {
    //   $.messager.alert("提示", '当前设备不在线，操作失败');
    //   disLoad();
    //   return;
    // }

    //打开/关闭设备
    // wx.request({
    //   url: m_set_dev_on_off_url,
    //   header: header,
    //   method: 'POST',
    //   success: res => {
    //     console.log(res, "开关合上协议发送成功!");
    //   },
    //   fail: function (error) {
    //     console.log(error, "error");
    //   },
    //   complete: function (complete) {

    //   }
    // });

    // let m_set_dev_auto_manual = '';
    /**cur_mode_array [手动，自动] */
    // if(that.data.cur_operator_index == 0){
    //   m_set_dev_auto_manual = "https://119.3.46.145/server/m_set_dev_manual?devId=" + that.data.devNo;
    // }
    // if (that.data.cur_operator_index == 1) {
    //   m_set_dev_auto_manual = "https://119.3.46.145/server/m_set_dev_auto?devId=" + that.data.devNo;
    // }

    // wx.request({
    //   url: m_set_dev_auto_manual,
    //   header: header,
    //   method: 'POST',
    //   success: res => {
    //     console.log(res, "开关协议发送成功");
       
    //   },
    //   fail: function (error) {
    //     console.log(error, "error");
    //   },
    //   complete: function (complete) {

    //   }
    // });

   

    if (that.data.before_firstTurnOnTime !== that.data.firstTurnOnTime || that.data.before_firstTurnOffTime !== that.dat.firstTurnOffTime) {
      try_times = 0;
      that.setTime(that.data.devNo, that.data.firstTurnOnTime, that.data.firstTurnOffTime);
    }

    if (that.data.before_longitude != that.data.longitude || that.data.before_latitude != that.data.latitude) {
      try_times = 0;
      setLocation(devNo, that.data.longitude, that.data.latitude);
    }

    /**第一路开关时间 第二路开关时间 协议 */
    // let light_on_off_url = 'https://119.3.46.145/server/m_set_dev_timer?devId=' + that.data.devNo + "&FirstTurnOnTime=" + that.data.firstTurnOnTime + "&FirstTurnOffTime=" + that.data.firstTurnOffTime + "&SecondTurnOnTime=" + that.data.secondTurnOnTime +"&SecondTurnOffTime="+that.data.secondTurnOffTime;
    // wx.request({
    //   url: light_on_off_url,
    //   header: header,
    //   method: 'POST',
    //   success: res => {
    //     console.log(res, "开关灯协议发送成功");

    //   },
    //   fail: function (error) {
    //     console.log(error, "error");
    //   },
    //   complete: function (complete) {

    //   }
    // });


    /**经纬度*/
    // let m_set_dev_location_url = 'https://119.3.46.145/server/m_set_dev_location?devId=' + that.data.devNo + "&longitude=" + that.data.longitude +"&latitude="+that.data.latitude;
    // wx.request({
    //   url: m_set_dev_location_url,
    //   header: header,
    //   method: 'POST',
    //   success: res => {
    //     console.log(res, "开关灯协议发送成功");
    //   },
    //   fail: function (error) {
    //     console.log(error, "error");
    //   },
    //   complete: function (complete) {

    //   }
    // });



    

  },



  /**模式选择器 触发函数 [手动，自动]*/
  bindModeChange:function(e){
    let that = this;
    that.setData({
      cur_mode_index:e.detail.value,
      cur_mode_item: e.detail.value?'自动':'手动'
    });    
  },

  /**开关选择出发函数 [合上，断开]*/
  bindSwitchChange:function(e){
    let that = this;
    that.setData({
      cur_operator_index:e.detail.value,
      cur_operator_item: e.detail.value ? '断开' : '合上'
    });
  },  

  /**第一路开灯时间 */
  firstTurnOnTimeChange:function(e){
    var that = this
    that.setData({
      firstTurnOnTime: e.detail.value + ":00"
    });
  },

  /**第一路关灯时间 */
  firstTurnoffTimeChange:function(e){
    var that = this
    that.setData({
      firstTurnOffTime: e.detail.value + ":00"
    });

  },

  /**第二路开灯时间 */
  secondTurnOnTimeChange:function(e){
    let that = this;
    that.setData({
      secondTurnOnTime:e.detail.value + ":00"
    });

    //console.log(that.data.secondTurnOnTime, "secondTurnOnTime");

  },

  /**第二路关灯时间 */
  secondTurnOffTimeChange:function(e){
    var that = this
    that.setData({
      secondTurnOffTime: e.detail.value + ":00"
    });
  },

  setTime:function(devNo, openTime, closeTime)
  {
    let that = this;
    that.load("请稍等...");

    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };   
      
    //openTime就是that.data.firstTurnOnTime  closeTime就是 that.data.firstTurnOffTime
    //let light_on_off_url = 'https://119.3.46.145/server/m_set_dev_timer?devId=' + that.data.devNo + "&FirstTurnOnTime=" + that.data.firstTurnOnTime + "&FirstTurnOffTime=" + that.data.firstTurnOffTime + "&SecondTurnOnTime=" + that.data.secondTurnOnTime +"&SecondTurnOffTime="+that.data.secondTurnOffTime;
    let light_on_off_url = 'https://119.3.46.145/server/m_set_dev_timer?devId=' + that.data.devNo + "&FirstTurnOnTime=" + openTime + "&FirstTurnOffTime=" + that.data.firstTurnOffTime + "&SecondTurnOnTime=" + that.data.secondTurnOnTime + "&SecondTurnOffTime=" + closeTime;
    wx.request({
      url: light_on_off_url,
      header: header,
      method: 'POST',
      success: res => {
        setTimeout(function () {
          // $.ajax({
          //   url: "/server/GetLastInfo",
          //   type: "post",
          //   data: {
          //     devNo: devNo
          //   },
          //   success: function (response) {
          //     let obj = JSON.parse(JSON.parse(response).data)[0];

          //     if ((obj.FirstTurnOnTime == openTime && obj.FirstTurnOffTime == closeTime)
          //       && (obj.SecondTurnOnTime == openTime && obj.SecondTurnOffTime == closeTime)) {
          //       alert("操作成功");
          //       disLoad();
          //     }
          //     else {
          //       try_times++;
          //       if (try_times <= retimes) {
          //         SetTime(devNo, openTime, closeTime);
          //       }
          //       else {
          //         try_times = 0;
          //         alert("操作失败");
          //         disLoad();
          //       }
          //     }

          //   }
          // });
          wx.request({
            url: "https://119.3.46.145/server/GetLastInfo?devNo=" + that.data.devNo,
            type: "post",
            header: header,
            success: res => {
              //加载隐藏              
              //that.disLoad();
              //let obj = JSON.parse(JSON.parse(response).data)[0];
              let obj = JSON.parse(res.data.data)[0];

              if ((obj.FirstTurnOnTime == openTime && obj.FirstTurnOffTime == closeTime)
                && (obj.SecondTurnOnTime == that.data.secondTurnOnTime && obj.SecondTurnOffTime == that.data.secondTurnOffTime)) {
                wx.showModal({
                  title: '提示',
                  content: '操作成功！'
                })
                that.disLoad();
              }
              else {
                try_times++;
                if (try_times <= retimes) {
                  that.setTime(devNo, openTime, closeTime);
                }
                else {
                  try_times = 0;
                  wx.showModal({
                    title: '提示',
                    content: '操作失败'
                  })
                  that.disLoad();
                }
              }
            },
            fail: error => {
              wx.showModal({
                title: '提示',
                content: '请求实时信息出错' + res
              })
            }
          })
        }, reInterval);
      },
      fail: function (error) {
        console.log(error, "error");
      }
    });
  },

  setLocation:function(devNo, lng, lati)
  {
    let that = this;
    that.load("等稍等...");
    // $.ajax({
    //   url: "/server/m_set_dev_location",
    //   type: "post",
    //   data: {
    //     devid: devNo,
    //     longitude: lng,
    //     latitude: lati
    //   },
    //   success: function () {
    //     setTimeout(function () {
    //       $.ajax({
    //         url: "/server/GetLastInfo",
    //         type: "post",
    //         data: {
    //           devNo: devNo
    //         },
    //         success: function (response) {
    //           let obj = JSON.parse(JSON.parse(response).data)[0];

    //           if (obj.Longitude !== currentInfo[0].Longitude || obj.Latitude !== currentInfo[0].Latitude) {
    //             alert("操作成功");
    //             disLoad();
    //           }
    //           else {
    //             try_times++;
    //             if (try_times <= retimes) {
    //               SetLocation(devNo, lng, lati);
    //             }
    //             else {
    //               try_times = 0;
    //               alert("操作失败");
    //               disLoad();
    //             }
    //           }

    //         }
    //       });
    //     }, reInterval);
    //   }
    // });
    // let m_set_dev_location_url = 'https://119.3.46.145/server/m_set_dev_location?devId=' + that.data.devNo + "&longitude=" + that.data.longitude +"&latitude="+that.data.latitude;  
    let m_set_dev_location_url = 'https://119.3.46.145/server/m_set_dev_location?devId=' + devNo + "&longitude=" + lng + "&latitude=" + lati;
    wx.request({
      url: m_set_dev_location_url,
      header: header,
      method: 'POST',
      success: res => {
        setTimeout(function () {
          // $.ajax({
          //   url: "/server/GetLastInfo",
          //   type: "post",
          //   data: {
          //     devNo: devNo
          //   },
          //   success: function (response) {
          //     let obj = JSON.parse(JSON.parse(response).data)[0];

          //     if (obj.Longitude !== currentInfo[0].Longitude || obj.Latitude !== currentInfo[0].Latitude) {
          //       alert("操作成功");
          //       disLoad();
          //     }
          //     else {
          //       try_times++;
          //       if (try_times <= retimes) {
          //         SetLocation(devNo, lng, lati);
          //       }
          //       else {
          //         try_times = 0;
          //         alert("操作失败");
          //         disLoad();
          //       }
          //     }
          //   }
          // });
          wx.request({
            url: "https://119.3.46.145/server/GetLastInfo?devNo=" + devNo,
            type: "post",
            header: header,
            success: res => {
              let obj = JSON.parse(res.data.data)[0];

              if (obj.Longitude !== that.data.before_longitude || obj.Latitude !== that.data.before_latitude) {
                wx.showModal({
                  title: '提示',
                  content: '操作成功' 
                });
                disLoad();
              }
              else {
                try_times++;
                if (try_times <= retimes) {
                  that.setLocation(devNo, lng, lati);
                }
                else {
                  try_times = 0;
                  wx.showModal({
                    title:"提示",
                    content: "操作失败"
                  });
                  that.disLoad();
                }
              }            
            },
            fail: error => {
              wx.showModal({
                title: '提示',
                content: '请求实时信息出错' + res
              })
            }
          });
        }, reInterval);
      },
      fail: function (error) {
        console.log(error, "error");
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
